Mybatis Plus最新代码生成器AutoGenerator,更简单更高效! 您所在的位置:网站首页 mybatis plus 的page Mybatis Plus最新代码生成器AutoGenerator,更简单更高效!

Mybatis Plus最新代码生成器AutoGenerator,更简单更高效!

#Mybatis Plus最新代码生成器AutoGenerator,更简单更高效!| 来源: 网络整理| 查看: 265

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。 今天的主角是MP推出的一款代码生成器,本文主要来介绍一下它强大的代码生成功能。 一、概述 AutoGenerator 是 MyBatis Plus推出的代码生成器,可以快速生成Entity、Mapper、Mapper XML、Service、Controller等各个模块的代码,比Mybatis Generator更强大,开发效率更高。

以往我们使用mybatis generator生成代码正常需要配置mybatis-generator-config.xml,代码配置比较繁琐复杂,比如:

二、使用AutoGenerator 1. 初始化数据库表结构(以User用户表为例)

SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for user -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `username` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '用户名', `mobile` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '手机号', `create_by` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建人', `create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间', PRIMARY KEY (`id`) USING BTREE, UNIQUE INDEX `username`(`username`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用户' ROW_FORMAT = Dynamic; SET FOREIGN_KEY_CHECKS = 1;

2. 在 pom.xml 文件中添加 AutoGenerator 的依赖。

com.baomidou mybatis-plus-generator 3.4.1

3. 添加模板引擎依赖,MyBatis-Plus 支持 Velocity(默认)、Freemarker、Beetl,这里使用Freemarker引擎。

com.baomidou mybatis-plus-generator 3.4.1

4. 全局配置

package com.shardingspherejdbc.mybatisplus.genertor; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.generator.FastAutoGenerator; import com.baomidou.mybatisplus.generator.config.OutputFile; import com.baomidou.mybatisplus.generator.config.rules.DateType; import com.baomidou.mybatisplus.generator.fill.Column; import com.baomidou.mybatisplus.generator.fill.Property; import com.shardingspherejdbc.mybatisplus.engine.EnhanceFreemarkerTemplateEngine; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * 代码生成器 * * @author: austin * @since: 2023/2/6 15:28 */ public class CodeGenerator { public static void main(String[] args) { // 数据源配置 FastAutoGenerator.create("jdbc:mysql://localhost:3306/sharding-db0?serverTimezone=GMT%2B8", "root", "admin") .globalConfig(builder -> { builder.author("austin") // 设置作者 .enableSwagger() // 开启 swagger 模式 默认值:false .disableOpenDir() // 禁止打开输出目录 默认值:true .commentDate("yyyy-MM-dd") // 注释日期 .dateType(DateType.ONLY_DATE) //定义生成的实体类中日期类型 DateType.ONLY_DATE 默认值: DateType.TIME_PACK .outputDir(System.getProperty("user.dir") + "/src/main/java"); // 指定输出目录 }) .packageConfig(builder -> { builder.parent("com.shardingspherejdbc.mybatisplus") // 父包模块名 .controller("controller") //Controller 包名 默认值:controller .entity("entity") //Entity 包名 默认值:entity .service("service") //Service 包名 默认值:service .mapper("mapper") //Mapper 包名 默认值:mapper .other("model") //.moduleName("xxx") // 设置父包模块名 默认值:无 .pathInfo(Collections.singletonMap(OutputFile.xml, System.getProperty("user.dir") + "/src/main/resources/mapper")); // 设置mapperXml生成路径 //默认存放在mapper的xml下 }) .injectionConfig(consumer -> { Map customFile = new HashMap(); // DTO、VO customFile.put("DTO.java", "/templates/entityDTO.java.ftl"); customFile.put("VO.java", "/templates/entityVO.java.ftl"); consumer.customFile(customFile); }) .strategyConfig(builder -> { builder.addInclude("user") // 设置需要生成的表名 可边长参数“user”, “user1” .addTablePrefix("tb_", "gms_") // 设置过滤表前缀 .serviceBuilder()//service策略配置 .formatServiceFileName("%sService") .formatServiceImplFileName("%sServiceImpl") .entityBuilder()// 实体类策略配置 .idType(IdType.ASSIGN_ID)//主键策略 雪花算法自动生成的id .addTableFills(new Column("create_time", FieldFill.INSERT)) // 自动填充配置 .addTableFills(new Property("update_time", FieldFill.INSERT_UPDATE)) .enableLombok() //开启lombok .logicDeleteColumnName("deleted")// 说明逻辑删除是哪个字段 .enableTableFieldAnnotation()// 属性加上注解说明 .controllerBuilder() //controller 策略配置 .formatFileName("%sController") .enableRestStyle() // 开启RestController注解 .mapperBuilder()// mapper策略配置 .formatMapperFileName("%sMapper") .enableMapperAnnotation()//@mapper注解开启 .formatXmlFileName("%sMapper"); }) // 使用Freemarker引擎模板,默认的是Velocity引擎模板 //.templateEngine(new FreemarkerTemplateEngine()) .templateEngine(new EnhanceFreemarkerTemplateEngine()) .execute(); } }

5. 自定义模板生成DTO、VO

package com.shardingspherejdbc.mybatisplus.engine; import com.baomidou.mybatisplus.generator.config.OutputFile; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; import org.springframework.stereotype.Component; import java.io.File; import java.util.Map; /** * 代码生成器支持自定义[DTO\VO等]模版 * * @author: austin * @since: 2023/2/9 13:00 */ @Component public class EnhanceFreemarkerTemplateEngine extends FreemarkerTemplateEngine { @Override protected void outputCustomFile(Map customFile, TableInfo tableInfo, Map objectMap) { String entityName = tableInfo.getEntityName(); String otherPath = this.getPathInfo(OutputFile.other); customFile.forEach((key, value) -> { String fileName = String.format(otherPath + File.separator + entityName + "%s", key); this.outputFile(new File(fileName), objectMap, value, true); }); } }

未生成代码前的项目目录如下:

运行CodeGenerator生成代码:

14:20:21.127 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - ==========================准备生成文件...========================== 14:20:22.053 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 执行SQL:show table status WHERE 1=1 AND NAME IN ('user') 14:20:22.081 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 返回记录数:1,耗时(ms):26 14:20:22.167 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 执行SQL:show full fields from `user` 14:20:22.171 [main] WARN com.baomidou.mybatisplus.generator.IDatabaseQuery$DefaultDatabaseQuery - 当前表[user]的主键为自增主键,会导致全局主键的ID类型设置失效! 14:20:22.182 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 返回记录数:5,耗时(ms):14 14:20:22.502 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - ==========================文件生成完成!!!==========================

项目成功生成了Entity、Service、Controller、Mapper、Mapper.xml、DTO、VO文件。

User用户类

package com.shardingspherejdbc.mybatisplus.entity; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.Setter; import java.io.Serializable; import java.util.Date; /** *

* 用户 *

* * @author austin * @since 2023-02-09 */ @Getter @Setter @TableName("user") @ApiModel(value = "User对象", description = "用户") public class User implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Long id; @ApiModelProperty("用户名") @TableField("username") private String username; @ApiModelProperty("手机号") @TableField("mobile") private String mobile; @ApiModelProperty("创建人") @TableField("create_by") private String createBy; @ApiModelProperty("创建时间") @TableField(value = "create_time", fill = FieldFill.INSERT) private Date createTime; }

想了解MyBatis Plus代码生成配置可以参考官方配置:代码生成器配置新

总结

对比Mybatis的Generator和MyBatis-Plus的AutoGenerator,就可以得出这样一条结论:后者的配置更简单,开发效率也更高,功能也更强大——可快速生成Mapper、Model、Service、Controller、DTO/VO层代码,到这里AutoGenerator生成器的介绍已经完成,希望文章对你有所帮助,我们下期见!



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有